package juc.reentrantreadwritelock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class MyService {
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    public void read(){
        try {
            // 加读锁
            lock.readLock().lock();
            System.out.println(Thread.currentThread().getName() + "获得读锁" + System.currentTimeMillis());
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.readLock().unlock();
        }
    }
    public void write(){
        try {
            // 加写锁
            lock.writeLock().lock();
            System.out.println(Thread.currentThread().getName() + "获得写锁" + System.currentTimeMillis());
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.writeLock().unlock();
        }
    }

}
